package gui;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Properties;

import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JButton;
import javax.swing.JComboBox;

import classes.ConnectionDB;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;

public class InsertTopicSubtopic extends JFrame {

	private JPanel contentPane;
	private JTextField topicField;
	private JTextField subField;
	private JTextField editedTopic;
	private JTextField EditedSubtopic;
	private String lastChosenTopic;
	private String lastSubTopicChosen;
	private JComboBox topicsBox;
	private JComboBox subtopicBox;
	private static boolean removeSubTopicsFlag;
	private static JFrame fr;
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					InsertTopicSubtopic frame = new InsertTopicSubtopic(null);
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 * 
	 * @throws SQLException
	 */
	public InsertTopicSubtopic(final Properties languageFile)
			throws SQLException {
		this.setExtendedState(JFrame.MAXIMIZED_BOTH);
		final Connection connection = new ConnectionDB().createConnection();
		fr = this;
		this.setUndecorated(true);
		final java.sql.Statement statemnt = connection.createStatement();

		setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
		setBounds(100, 100, 450, 300);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);

		JLabel lblAddTopicAndor = new JLabel(
				languageFile.getProperty("usr.menu.file.addTopics"));
		lblAddTopicAndor.setFont(new Font("Tahoma", Font.BOLD, 18));
		lblAddTopicAndor.setHorizontalAlignment(SwingConstants.CENTER);

		JLabel lblTopic = new JLabel(
				languageFile.getProperty("usr.menu.file.addTopic.topic"));
		lblTopic.setFont(new Font("Tahoma", Font.BOLD, 15));

		topicField = new JTextField();
		topicField.setColumns(10);

		JButton btnAddTopic = new JButton(
				languageFile.getProperty("usr.menu.file.addTopic.addBtn"));
		btnAddTopic.setFont(new Font("Tahoma", Font.BOLD, 11));
		btnAddTopic.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				if (topicField.getText().isEmpty()) {
					JFrame frame = new JFrame(
							"JOptionPane showMessageDialog example");
					JOptionPane.showMessageDialog(
							frame,
							languageFile
									.getProperty("usr.menu.file.addTopic.alert.noTopicName"));
				} else {
					try {
						java.sql.PreparedStatement stat = connection
								.prepareStatement("SELECT subtopic FROM TOPSUB WHERE topic = ?");
						String topic = topicField.getText();
						stat.setString(1, topic);
						ResultSet res = stat.executeQuery();
						if (res.next()) {
							JFrame frame = new JFrame(
									"JOptionPane showMessageDialog example");
							JOptionPane.showMessageDialog(
									frame,
									languageFile
											.getProperty("usr.menu.file.addTopic.alert.topicAlreadyExist"));
							topicField.setText("");
						} else {
							statemnt.executeUpdate("INSERT INTO TOPSUB VALUES ('"
									+ topicField.getText() + "', NULL)");
							JFrame frame = new JFrame(
									"JOptionPane showMessageDialog example");
							JOptionPane.showMessageDialog(
									frame,
									languageFile
											.getProperty("usr.menu.file.addTopic.alert.topicAdded"));
							topicField.setText("");
						}
					} catch (SQLException e1) {
						e1.printStackTrace();
					}
					;
				}
			}
		});

		JLabel lblChooseTopic = new JLabel(
				languageFile.getProperty("usr.menu.file.addTopic.chooseTopic"));
		lblChooseTopic.setFont(new Font("Tahoma", Font.BOLD, 15));

		final JComboBox topicChosen = new JComboBox();
		topicsBox = topicChosen;
		topicsBox.addItem("--------");
		topicsBox.addFocusListener(new FocusAdapter() {
			@Override
			public void focusGained(FocusEvent arg0) {
				try {
					refreshTopicList();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		});

		final JLabel lblSubtopic = new JLabel(
				languageFile.getProperty("usr.menu.file.addTopic.Addsubtopic"));
		lblSubtopic.setFont(new Font("Tahoma", Font.BOLD, 15));

		subField = new JTextField();
		subField.setColumns(10);

		JButton btnAddSubtopic = new JButton(
				languageFile.getProperty("usr.menu.file.addTopic.addSub"));
		btnAddSubtopic.setFont(new Font("Tahoma", Font.BOLD, 11));
		btnAddSubtopic.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				java.sql.PreparedStatement stat;
				String selectedTopic = (String) topicChosen.getSelectedItem();
				if (subField.getText().isEmpty()
						|| selectedTopic.equals("--------")) {
					JFrame frame = new JFrame(
							"JOptionPane showMessageDialog example");
					JOptionPane.showMessageDialog(
							frame,
							languageFile
									.getProperty("usr.menu.file.addTopic.alert.noSubtopicName"));
				} else {
					try {
						stat = connection
								.prepareStatement("SELECT subtopic FROM TOPSUB WHERE subtopic = ?");
						String topic = subField.getText();
						stat.setString(1, topic);
						ResultSet res = stat.executeQuery();
						if (res.next()) {
							JFrame frame = new JFrame(
									"JOptionPane showMessageDialog example");
							JOptionPane.showMessageDialog(
									frame,
									languageFile
											.getProperty("usr.menu.file.addTopic.alert.subtopicAlreadyExist"));
							subField.setText("");
						}

						else {
							statemnt.executeUpdate("INSERT INTO TOPSUB VALUES ('"
									+ selectedTopic
									+ "','"
									+ subField.getText() + "')");
							JFrame frame = new JFrame(
									"JOptionPane showMessageDialog example");
							JOptionPane.showMessageDialog(
									frame,
									languageFile
											.getProperty("usr.menu.file.addTopic.alert.SubtopicAdded"));
							subtopicBox.addItem(subField.getText());
							subField.setText("");
						}

					} catch (SQLException e1) {
						System.out.println("SQL Exception");
						e1.printStackTrace();
					}
				}
			}
		});

		JLabel lblSubtopic_1 = new JLabel(
				languageFile.getProperty("usr.menu.file.addTopic.subtopic"));
		lblSubtopic_1.setFont(new Font("Tahoma", Font.BOLD, 15));

		final JComboBox subtopicChosen = new JComboBox();
		subtopicBox = subtopicChosen;
		subtopicChosen.setMaximumRowCount(15);
		subtopicChosen.addItem("--------");

		final JButton subEditBtn = new JButton(
				languageFile.getProperty("usr.menu.file.addTopic.edit"));
		subEditBtn.setVisible(false);
		final JButton topicEditBtn = new JButton(
				languageFile.getProperty("usr.menu.file.addTopic.edit"));
		topicEditBtn.setVisible(false);

		final JButton subtopicRemoveBtn = new JButton(
				languageFile.getProperty("usr.menu.file.addTopic.remove"));
		subtopicRemoveBtn.setVisible(false);
		final JButton topicRemoveBtn = new JButton(
				languageFile.getProperty("usr.menu.file.addTopic.remove"));
		topicRemoveBtn.setVisible(false);

		editedTopic = new JTextField();
		editedTopic.setColumns(15);
		editedTopic.setVisible(false);
		EditedSubtopic = new JTextField();
		EditedSubtopic.setColumns(15);
		EditedSubtopic.setVisible(false);

		topicRemoveBtn.addActionListener(new ActionListener() {
			java.sql.PreparedStatement statMent;

			@Override
			public void actionPerformed(ActionEvent e) {
				JFrame frame = new JFrame(
						"JOptionPane showMessageDialog example");
				if (lastChosenTopic.equals("--------")) {
					JOptionPane.showMessageDialog(
							frame,
							languageFile
									.getProperty("usr.menu.file.addTopic.alert.chooseTopic"));
				}
				else{
				if (JOptionPane.showConfirmDialog(frame,
						languageFile.getProperty("usr.menu.file.addTopic.alert.delete") +" " + lastChosenTopic
								+ " " +languageFile.getProperty("usr.menu.file.addTopic.alert.allsub")+ " ?", "Alert",
						JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
					try {
						statMent = connection
								.prepareStatement("DELETE FROM TOPSUB WHERE topic = ?");
						statMent.setString(1, lastChosenTopic);
						statMent.executeUpdate();
						JOptionPane.showMessageDialog(
								frame,
								languageFile
										.getProperty("usr.menu.file.addTopic.alert.topicRemoved"));
						topicsBox.removeItem(lastChosenTopic);
					} catch (SQLException e1) {
						e1.printStackTrace();
					}
				}
			}
			}
		});

		subtopicBox.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				lastSubTopicChosen = (String)subtopicBox.getSelectedItem();
				if(!removeSubTopicsFlag || lastSubTopicChosen != null){				
				removeSubTopicsFlag = false;
				if(!lastSubTopicChosen.equals("--------")){
					EditedSubtopic.setVisible(true);
					subtopicRemoveBtn.setVisible(true);
					subEditBtn.setVisible(true);
				}
				}
			}
		});
		
		subtopicRemoveBtn.addActionListener(new ActionListener() {
			java.sql.PreparedStatement statMent;

			@Override
			public void actionPerformed(ActionEvent e) {
				String pressedItem = (String) subtopicBox.getSelectedItem();
				JFrame frame = new JFrame(
						"JOptionPane showMessageDialog example");
				if (lastSubTopicChosen.equals("--------")) {
					JOptionPane.showMessageDialog(
							frame,
							languageFile
									.getProperty("usr.menu.file.addTopic.alert.chooseSubTopic"));
				}
				else
				{
				if (JOptionPane.showConfirmDialog(frame,
						"Are you sure you want to delete" + pressedItem + "?",
						"Delete Alert", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
					try {

						statMent = connection
								.prepareStatement("DELETE FROM TOPSUB WHERE subtopic = ?");
						statMent.setString(1, pressedItem);
						statMent.executeUpdate();
						JOptionPane.showMessageDialog(
								frame,
								languageFile
										.getProperty("usr.menu.file.addTopic.alert.subtopicRemoved"));

						try {
							subtopicBox.removeItem(pressedItem);
						} catch (Exception ex) {
							System.out.println("Exception");
						}
					} catch (SQLException e1) {
						e1.printStackTrace();
					}
				}
				}
			}
		});

		topicChosen.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {

				String chosen = (String) topicChosen.getSelectedItem();
				lastChosenTopic = chosen;

				if (!chosen.equals("--------")) {
					topicEditBtn.setVisible(true);
					topicRemoveBtn.setVisible(true);
					editedTopic.setVisible(true);
					removeSubTopicsFlag = true;
					subtopicChosen.removeAllItems();
					subtopicChosen.addItem("--------");
					java.sql.PreparedStatement statMent;
					try {
						statMent = connection
								.prepareStatement("SELECT subtopic FROM TOPSUB WHERE topic = ? AND NOT(subtopic IS NULL)");
						statMent.setString(1, lastChosenTopic);
						ResultSet res = statMent.executeQuery();

						ArrayList<String> subTopics = new ArrayList<String>();

						while (res.next()) {
							subTopics.add(res.getString("subtopic"));
						}

						for (String s : subTopics) {
							subtopicChosen.addItem(s);
						}
					} catch (SQLException e1) {
						e1.printStackTrace();
					}
				}

			}
		});

		topicEditBtn.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				JFrame frame = new JFrame(
						"JOptionPane showMessageDialog example");
				if (lastChosenTopic.equals("--------")) {
					JOptionPane.showMessageDialog(
							frame,
							languageFile
									.getProperty("usr.menu.file.addTopic.alert.chooseTopic"));
				} else {
					if (editedTopic.getText().isEmpty()) {
						JOptionPane.showMessageDialog(
								frame,
								languageFile
										.getProperty("usr.menu.file.addTopic.alert.insertEditTopic"));
					} else {
						if (JOptionPane.showConfirmDialog(frame,
								languageFile.getProperty("usr.menu.file.addTopic.alert.replace")+" "
										+ lastChosenTopic + " " +languageFile.getProperty("usr.menu.file.addTopic.alert.with")
										+" "+ editedTopic.getText() + " ?",
								"Alert", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
							PreparedStatement statMent;
							try {
								statMent = connection
										.prepareStatement("UPDATE TOPSUB SET topic = ? WHERE topic = ?");
								statMent.setString(1, editedTopic.getText());
								statMent.setString(2,lastChosenTopic);
								statMent.executeUpdate();
								statMent = connection
										.prepareStatement("UPDATE SAVEQA SET topic = ? WHERE topic = ?");
								statMent.setString(1, editedTopic.getText());
								statMent.setString(2,lastChosenTopic);
								statMent.executeUpdate();
								
								JOptionPane.showMessageDialog(
										frame,
										languageFile
												.getProperty("usr.menu.file.addTopic.alert.topicEdited"));
								topicsBox.removeItem(lastChosenTopic);
								editedTopic.setText("");
							} catch (SQLException e1) {
								e1.printStackTrace();
							}
						}
					}
				}
			}
		});
		
		subEditBtn.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				JFrame frame = new JFrame(
						"JOptionPane showMessageDialog example");
				if (lastSubTopicChosen.equals("--------")) {
					JOptionPane.showMessageDialog(
							frame,
							languageFile
									.getProperty("usr.menu.file.addTopic.alert.chooseSubTopic"));
				} else {
					if (EditedSubtopic.getText().isEmpty()) {
						JOptionPane.showMessageDialog(
								frame,
								languageFile
										.getProperty("usr.menu.file.addTopic.alert.insertEditsubTopic"));
					} else {
						if (JOptionPane.showConfirmDialog(frame,
								languageFile.getProperty("usr.menu.file.addTopic.alert.replace")+" "
										+ lastSubTopicChosen + " " +languageFile.getProperty("usr.menu.file.addTopic.alert.with")
										+" "+ EditedSubtopic.getText() + " ?",
								"Alert", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
							PreparedStatement statMent;
							try {
								statMent = connection
										.prepareStatement("UPDATE TOPSUB SET subtopic = ? WHERE subtopic = ?");
								statMent.setString(1, EditedSubtopic.getText());
								statMent.setString(2,lastSubTopicChosen);
								statMent.executeUpdate();
								statMent = connection
										.prepareStatement("UPDATE SAVEQA SET subtopic = ? WHERE subtopic = ?");
								statMent.setString(1, EditedSubtopic.getText());
								statMent.setString(2,lastSubTopicChosen);
								statMent.executeUpdate();
								
								JOptionPane.showMessageDialog(
										frame,
										languageFile
												.getProperty("usr.menu.file.addTopic.alert.subtopicEdited"));
								subtopicBox.removeItem(lastSubTopicChosen);
								subtopicBox.addItem(EditedSubtopic.getText());
								EditedSubtopic.setText("");
							} catch (SQLException e1) {
								e1.printStackTrace();
							}
						}
					}
				}
			}
		});
		
		JButton btnBack = new JButton(languageFile.getProperty("usr.menu.backToMainMenu"));
		btnBack.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				fr.setVisible(false);
			}
		});
		GroupLayout gl_contentPane = new GroupLayout(contentPane);
		gl_contentPane.setHorizontalGroup(
			gl_contentPane.createParallelGroup(Alignment.TRAILING)
				.addGroup(gl_contentPane.createSequentialGroup()
					.addContainerGap()
					.addComponent(lblAddTopicAndor, GroupLayout.DEFAULT_SIZE, 631, Short.MAX_VALUE)
					.addGap(50))
				.addGroup(gl_contentPane.createSequentialGroup()
					.addGap(28)
					.addGroup(gl_contentPane.createParallelGroup(Alignment.TRAILING)
						.addComponent(btnAddTopic)
						.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
							.addComponent(btnBack)
							.addGroup(gl_contentPane.createSequentialGroup()
								.addComponent(lblTopic)
								.addGap(12)
								.addComponent(topicField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))))
					.addPreferredGap(ComponentPlacement.RELATED, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
					.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
						.addGroup(gl_contentPane.createParallelGroup(Alignment.TRAILING)
							.addComponent(btnAddSubtopic)
							.addGroup(gl_contentPane.createSequentialGroup()
								.addComponent(lblSubtopic)
								.addPreferredGap(ComponentPlacement.RELATED)
								.addComponent(subField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))
						.addGroup(gl_contentPane.createSequentialGroup()
							.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
								.addComponent(lblChooseTopic)
								.addComponent(lblSubtopic_1))
							.addPreferredGap(ComponentPlacement.RELATED)
							.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
								.addComponent(subtopicChosen, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
								.addComponent(topicChosen, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
							.addPreferredGap(ComponentPlacement.RELATED)
							.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
								.addGroup(gl_contentPane.createSequentialGroup()
									.addComponent(subEditBtn)
									.addPreferredGap(ComponentPlacement.RELATED)
									.addComponent(EditedSubtopic, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
									.addPreferredGap(ComponentPlacement.RELATED)
									.addComponent(subtopicRemoveBtn))
								.addGroup(gl_contentPane.createSequentialGroup()
									.addComponent(topicEditBtn)
									.addPreferredGap(ComponentPlacement.RELATED)
									.addComponent(editedTopic, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
									.addPreferredGap(ComponentPlacement.RELATED)
									.addComponent(topicRemoveBtn)))))
					.addContainerGap())
		);
		gl_contentPane.setVerticalGroup(
			gl_contentPane.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_contentPane.createSequentialGroup()
					.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
						.addGroup(gl_contentPane.createSequentialGroup()
							.addComponent(lblAddTopicAndor)
							.addGap(63)
							.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
								.addComponent(lblTopic)
								.addComponent(topicField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
								.addComponent(lblChooseTopic)
								.addComponent(topicChosen, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
								.addComponent(topicEditBtn)
								.addComponent(topicRemoveBtn)
								.addComponent(editedTopic, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
							.addPreferredGap(ComponentPlacement.RELATED)
							.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
								.addComponent(lblSubtopic_1)
								.addComponent(subtopicChosen, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
								.addComponent(subEditBtn)
								.addComponent(subtopicRemoveBtn)
								.addComponent(EditedSubtopic, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
							.addGap(21)
							.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
								.addComponent(lblSubtopic)
								.addComponent(subField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
								.addComponent(btnAddTopic))
							.addGap(31)
							.addComponent(btnAddSubtopic))
						.addGroup(gl_contentPane.createSequentialGroup()
							.addContainerGap()
							.addComponent(btnBack)))
					.addContainerGap(21, Short.MAX_VALUE))
		);
		contentPane.setLayout(gl_contentPane);
	}

	public void refreshTopicList() throws SQLException {
		final Connection connection = new ConnectionDB().createConnection();

		final java.sql.Statement statemnt = connection.createStatement();
		ResultSet ress;
		try {
			ress = statemnt.executeQuery("SELECT DISTINCT topic FROM TOPSUB");
			ArrayList<String> topics = new ArrayList<String>();

			while (ress.next()) {
				topics.add(ress.getString("topic"));
			}
			int i = 0;
			String item = (String) topicsBox.getItemAt(i);
			while (item != null) {
				if (topics.contains(item))
					topics.remove(item);
				i++;
				item = (String) topicsBox.getItemAt(i);
			}
			for (String str : topics) {
				topicsBox.addItem(str);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
